#pragma once
#include "DatabaseManager.h"
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QDebug>
#include <QThread>
#include <stdexcept>

class SessionGuard
{
public:
    explicit SessionGuard(const QString& poolName = "default", int retries = 3)
        : m_pool(DatabaseManager::instance().pool(poolName))
    {

        DatabaseManager& dbManager = DatabaseManager::instance();
        // 确保连接池存在
        if (!dbManager.hasPool(poolName))
        {
            dbManager.addDatabase(poolName);
        }

        m_pool = dbManager.pool(poolName);
        if (!m_pool)
        {
            throw std::runtime_error("Connection pool not found: " + poolName.toStdString());
        }

        // 尝试获取连接
        for (int i = 0; i < retries; ++i)
        {
            m_db = m_pool->getConnection();
            if (m_db.isOpen())
            {
                return; // 成功获取连接
            }
            if (i == retries - 1)
            {
                throw std::runtime_error("Failed to get database connection after " + std::to_string(retries) + " retries");
            }
        }
    }

    ~SessionGuard()
    {
        try
        {
            if (m_db.isOpen())
            {
                rollback();

                if (m_pool)
                {
                    // 确保连接状态被正确清理
                    m_pool->cleanupSession(m_db);
                    m_pool->releaseConnection(m_db);
                }
            }
        }
        catch (const std::exception& e)
        {
            qCritical() << "Error during connection release: " << QString::fromStdString(e.what());
        }
        catch (...)
        {
            qCritical() << "Unknown error during connection release";
        }
    }

    // 显式开启事务
    void beginTransaction()
    {
        if (m_committed)
        {
            throw std::logic_error("Cannot begin transaction after commit");
        }
        if (m_transactionBegun)
        {
            throw std::logic_error("Transaction already begun");
        }

        if (!m_db.transaction())
        {
            throw std::runtime_error("Failed to start transaction: " +
                                     m_db.lastError().text().toStdString());
        }
        m_transactionBegun = true;
    }

    void commit()
    {
        if (m_committed) return;

        int retries = 3;
        bool commitSuccess = false;

        for (int i = 0; i < retries; ++i)
        {
            if (m_db.commit())
            {
                commitSuccess = true;
                m_committed = true;
                break;
            }
            else
            {
                qWarning() << "Commit failed (attempt" << i + 1 << "of" << retries
                           << "):" << m_db.lastError().text();
                QThread::msleep(50);
            }
        }

        if (!commitSuccess)
        {
            qCritical() << "Failed to commit transaction after" << retries
                        << "retries, rolling back";
            if (!m_db.rollback())
            {
                qCritical() << "Rollback also failed:" << m_db.lastError().text();
            }
            throw std::runtime_error("Commit transaction failed");
        }
    }

    // 回滚事务（可选方法）
    void rollback()
    {
        if (!m_transactionBegun)
        {
            return; // 没有事务，无需回滚
        }

        if (m_db.rollback())
        {
            m_transactionBegun = false;
            m_committed = false;
        }

    }

    QSqlDatabase& database()
    {
        return m_db;
    }

private:
    QSqlDatabase m_db;
    ConnectionPool* m_pool;
    bool m_committed = false;
    bool m_transactionBegun = false; // 标记事务是否已开启
};
